package backed.controller;

import backed.dto.QARequest;
import backed.dto.GeneratePlanRequest;
import backed.service.AiService;
import backed.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * AI控制器 - 处理AI相关的HTTP请求
 * 功能：1. 环保知识问答  2. 生成个性化环保方案
 */
@io.swagger.v3.oas.annotations.tags.Tag(name = "AI智能体", description = "AI环保知识问答和个性化方案生成接口")
@RestController
@CrossOrigin
@RequestMapping("/api/ai")
public class AiController {

    @Autowired
    private AiService aiService;
    
    @Autowired
    private UserService userService;

    /**
     * 接口1：环保知识问答
     * 用户提问，AI回答环保相关问题
     */
    @Operation(summary = "环保知识问答智能体（Coze Bot）", description = "使用AI智能体回答用户关于环保知识的提问。请求参数示例：{\"userId\":1,\"question\":\"如何减少碳排放？\"}")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "问答成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "AI服务调用失败")
    })
    @PostMapping("/qa")
    public Object answerQuestion(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "问答请求参数",
                    required = true,
                    content = @Content(schema = @Schema(implementation = QARequest.class))
            )
            @RequestBody QARequest request) {
        try {
            // 步骤1：检查参数是否完整
            if (request == null || request.getUserId() == null || request.getQuestion() == null || request.getQuestion().isEmpty()) {
                throw new RuntimeException("缺少必需参数: userId 或 question");
            }

            // 步骤2：获取参数
            Long userId = request.getUserId();
            String question = request.getQuestion();

            // 步骤2.5：验证用户是否存在
            if (userService.getUserInfo(userId) == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户不存在，用户ID: " + userId);
                return new org.springframework.http.ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }

            // 步骤3：调用AI服务获取答案
            Map<String, Object> result = aiService.answerQuestion(userId, question);
            
            // 步骤4：检查AI返回的答案中是否有错误信息
            if (hasErrorInAnswer(result)) {
                return buildErrorResponse(question, getAnswerFromResult(result));
            }
            
            // 步骤5：返回成功结果
            return result;
            
        } catch (Exception e) {
            // 如果发生任何错误，返回错误信息
            return buildErrorResponse("系统错误：" + e.getMessage());
        }
    }

    /**
     * 接口2：生成个性化环保方案
     * 根据用户信息（地区、家庭人数、出行方式）生成专属环保方案
     * 
     * 支持两种调用方式：
     * 方式1：直接提供 context（简单方式）
     * 方式2：提供详细参数 userId, region, familySize, transportMode（推荐方式）
     */
    @Operation(summary = "生成个性化环保方案（Coze Bot）", description = "根据用户信息生成个性化的环保行动方案。支持两种方式：1.直接提供context；2.提供userId、region、familySize、transportMode参数。示例：{\"userId\":1,\"region\":\"北京\",\"familySize\":3,\"transportMode\":\"地铁\"}")
    @io.swagger.v3.oas.annotations.responses.ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "方案生成成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "用户不存在"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "500", description = "AI服务调用失败")
    })
    @PostMapping("/generate-plan")
    public Object generateEcoPlan(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "生成方案请求参数",
                    required = true,
                    content = @Content(schema = @Schema(implementation = GeneratePlanRequest.class))
            )
            @RequestBody GeneratePlanRequest request) {
        try {
            Long userId;
            String context;
            
            // 判断使用哪种方式
            if (request.getContext() != null && !request.getContext().isEmpty()) {
                // 方式1：直接提供context
                context = request.getContext();
                userId = request.getUserId();
                
                // 验证userId是否提供
                if (userId == null) {
                    throw new RuntimeException("缺少必需参数: userId");
                }
            } else {
                // 方式2：提供详细参数，需要先验证
                if (request.getUserId() == null || request.getRegion() == null || 
                    request.getFamilySize() == null || request.getTransportMode() == null) {
                    throw new RuntimeException("缺少必需参数: userId, region, familySize, transportMode");
                }
                
                userId = request.getUserId();
                String region = request.getRegion();
                Integer familySize = request.getFamilySize();
                String transportMode = request.getTransportMode();
                
                // 把详细参数组合成context字符串
                context = String.format("地区：%s，家庭人数：%d，出行方式：%s", 
                                       region, familySize, transportMode);
            }
            
            // 验证用户是否存在（userId必须存在且有效）
            if (userService.getUserInfo(userId) == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户不存在，用户ID: " + userId);
                return new org.springframework.http.ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
            }
            
            // 准备传递给service的参数
            String region = null;
            Integer familySize = null;
            String transportMode = null;
            
            // 如果使用的是方式2（详细参数），提取这些参数
            if (request.getRegion() != null && request.getFamilySize() != null && request.getTransportMode() != null) {
                region = request.getRegion();
                familySize = request.getFamilySize();
                transportMode = request.getTransportMode();
            }
            
            // 调用AI服务生成方案
            Map<String, Object> result = aiService.generatePlan(userId, region, familySize, transportMode);
            
            // 检查AI返回的方案中是否有错误信息
            if (hasErrorInPlan(result)) {
                return buildErrorResponse(context, getPlanContentFromResult(result));
            }
            
            // 返回成功结果（方案已由service层保存到数据库）
            return result;
            
        } catch (Exception e) {
            // 如果发生任何错误，返回错误信息
            return buildErrorResponse("系统错误：" + e.getMessage());
        }
    }


    // ==================== 工具方法 ====================
    
    /**
     * 检查答案中是否包含错误信息
     */
    private boolean hasErrorInAnswer(Map<String, Object> result) {
        if (result == null) return false;
        
        Object dataObj = result.get("data");
        if (!(dataObj instanceof Map)) return false;
        
        Map<String, Object> data = (Map<String, Object>) dataObj;
        Object answerObj = data.get("answer");
        if (!(answerObj instanceof String)) return false;
        
        String answer = (String) answerObj;
        return containsErrorKeywords(answer);
    }
    
    /**
     * 检查方案中是否包含错误信息
     */
    private boolean hasErrorInPlan(Map<String, Object> result) {
        if (result == null) return false;
        
        Object dataObj = result.get("data");
        if (!(dataObj instanceof Map)) return false;
        
        Map<String, Object> data = (Map<String, Object>) dataObj;
        Object planObj = data.get("planContent");
        if (!(planObj instanceof String)) return false;
        
        String planContent = (String) planObj;
        return containsErrorKeywords(planContent);
    }
    
    /**
     * 检查文本中是否包含错误关键词
     */
    private boolean containsErrorKeywords(String text) {
        return text.contains("error") || 
               text.contains("4101") || 
               text.contains("incorrect") || 
               text.contains("认证失败") ||
               text.contains("The token you entered is incorrect");
    }
    
    /**
     * 从结果中提取答案
     */
    private String getAnswerFromResult(Map<String, Object> result) {
        Map<String, Object> data = (Map<String, Object>) result.get("data");
        return (String) data.get("answer");
    }
    
    /**
     * 从结果中提取方案内容
     */
    private String getPlanContentFromResult(Map<String, Object> result) {
        Map<String, Object> data = (Map<String, Object>) result.get("data");
        return (String) data.get("planContent");
    }
    
    /**
     * 构建错误响应（简单版本）
     */
    private Map<String, Object> buildErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
    
    /**
     * 构建错误响应（带原始数据）
     */
    private Map<String, Object> buildErrorResponse(String context, String originalResponse) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", "AI服务调用失败：认证信息无效或权限不足");
        response.put("data", Map.of(
            "context", context,
            "originalResponse", originalResponse
        ));
        return response;
    }
}
